package com.stars.easyms.logger.support.logback.sift;

import ch.qos.logback.classic.sift.SiftingAppender;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.joran.action.Action;
import ch.qos.logback.core.joran.event.InPlayListener;
import ch.qos.logback.core.joran.event.SaxEvent;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import ch.qos.logback.core.sift.AppenderFactory;
import com.stars.easyms.logger.support.EasyMsOverride;
import com.stars.easyms.logger.support.logback.appender.EasyMsUnsynchronizedSiftingAppender;
import org.xml.sax.Attributes;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>className: EasyMsSiftAction</p>
 * <p>description: 重写SiftAction类</p>
 *
 * @author guoguifang
 * @date 2019-08-20 16:20
 * @since 1.3.0
 */
public final class EasyMsSiftAction extends Action implements InPlayListener, EasyMsOverride {

    private List<SaxEvent> seList;

    @Override
    public void begin(InterpretationContext ic, String name, Attributes attributes) {
        seList = new ArrayList<>();
        ic.addInPlayListener(this);
    }

    @Override
    public void end(InterpretationContext ic, String name) {
        ic.removeInPlayListener(this);
        Object o = ic.peekObject();
        if (o instanceof SiftingAppender) {
            SiftingAppender sa = (SiftingAppender) o;
            Map<String, String> propertyMap = ic.getCopyOfPropertyMap();
            AppenderFactory<ILoggingEvent> appenderFactory = new EasyMsAppenderFactoryUsingJoran(seList, sa.getDiscriminatorKey(), propertyMap);
            sa.setAppenderFactory(appenderFactory);
        } else if (o instanceof EasyMsUnsynchronizedSiftingAppender) {
            EasyMsUnsynchronizedSiftingAppender unsynchronizedSiftingAppender = (EasyMsUnsynchronizedSiftingAppender) o;
            Map<String, String> propertyMap = ic.getCopyOfPropertyMap();
            AppenderFactory<ILoggingEvent> appenderFactory = new EasyMsAppenderFactoryUsingJoran(seList, unsynchronizedSiftingAppender.getDiscriminatorKey(), propertyMap);
            unsynchronizedSiftingAppender.setAppenderFactory(appenderFactory);
        }
    }

    @Override
    public void inPlay(SaxEvent event) {
        seList.add(event);
    }

    public List<SaxEvent> getSeList() {
        return seList;
    }

}